import { AxiosProgressEvent } from "axios";
import httpRequest from "..";
import { UploadFileParams } from "../http/request";

/**
 * 普通文件上传请求
 * @param {UploadFileParams}fileInfo File对象和一些其他表单字段
 * @param {Function}onUploadProgress 上传进度回调
 * @param {AbortSignal}signal 取消请求 signal
 * @returns httpRequest.uploadFile()
 */
export function uploadFileReq(
    fileInfo: UploadFileParams,
    onUploadProgress?: (event: AxiosProgressEvent) => void,
    signal?: AbortSignal
) {
    return httpRequest.uploadFile(
        {
            baseURL: import.meta.env.VITE_APP_UPLOAD_BASE_URL,
            url: "/upload"
        },
        fileInfo,
        onUploadProgress,
        signal
    );
}

/**
 * 大文件分片上传请求
 * @param {UploadFileParams}fileInfo File对象和一些其他表单字段
 * @param {Function}onUploadProgress 上传进度回调
 * @param {AbortSignal}signal 取消请求 signal
 * @returns httpRequest.uploadFile()
 */
export function uploadChunkReq(
    fileInfo: UploadFileParams,
    onUploadProgress?: (event: AxiosProgressEvent) => void,
    signal?: AbortSignal
) {
    return httpRequest.uploadFile<any>(
        {
            baseURL: import.meta.env.VITE_APP_UPLOAD_BASE_URL,
            url: "/upload/chunk"
        },
        fileInfo,
        onUploadProgress,
        signal
    );
}

/**
 * 合并分片
 * @param {string}fileHash 文件hash
 * @param {string}filename 文件名
 * @param {number}chunkSize 分片大小（Byte）
 * @returns
 */
export function mergeChunkReq(fileHash: string, filename: string, chunkSize: number) {
    return httpRequest.post({
        baseURL: import.meta.env.VITE_APP_UPLOAD_BASE_URL,
        url: "/upload/merge",
        data: {
            fileHash,
            filename,
            chunkSize
        }
    });
}

/**
 * 验证文件是否上传
 * 已上传：返回访问链接
 * 未上传或上传了一部分：返回已经完全上传的分片（最后一片除外）
 * @param fileHash 文件hash
 * @param chunkSize 分片大小（Byte）
 * @returns Promise
 */
export function verifyFileUploadedReq(fileHash: string, chunkSize: number) {
    return httpRequest.post({
        baseURL: import.meta.env.VITE_APP_UPLOAD_BASE_URL,
        url: "/upload/verify",
        data: {
            fileHash,
            chunkSize
        }
    });
}

/**
 * 获取文件下载地址
 * @param fileHash 文件hash
 * @returns
 */
export function getFileReq(fileHash: string) {
    return httpRequest.get({
        baseURL: import.meta.env.VITE_APP_UPLOAD_BASE_URL,
        url: `/${fileHash}`
    });
}
